package com.boarsoft.message.test.activemq;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.boarsoft.common.util.RandomUtil;
import com.boarsoft.message.bean.Message;

/**
 * 此类演示了如何使用ActiveMQ/JMS 短连接作为消息发送方式
 * 
 * @author Mac_J
 *
 */
public class AmqPubTest1 {
	private static final Logger log = LoggerFactory.getLogger(AmqPubTest1.class);
	
	public static void main(String[] args) throws Exception {
		// 可以使用ActiveMQ API来创建连接工厂
//		ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616");
		ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("http://localhost:8080?trace=true");
		// 也可以使用JMS API来创建连接工厂
		// JmsConnectionFactory factory = new
		// JmsConnectionFactory("amqp://127.0.0.1:5672");
		// JmsConnectionFactory factory = new
		// JmsConnectionFactory("tcp://127.0.0.1:61616");
		Connection connection = factory.createConnection("admin", "admin");
		// connection.setClientID("demo");
		connection.start();
		final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		Destination destination = session.createQueue("queue1");
		final MessageProducer producer = session.createProducer(destination);
		producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
		try {
			Message m = new Message();
			m.setTarget("queue1");
			m.setContent("Hello world!");
			// 采用ActiveMQ/JMS方式时，是否需要设置收件人，取决于消息者如何处理
			m.addRecipient("queue1Consumer1");
			m.setId(RandomUtil.genUUID());
			log.info("Send message {}", m);
			TextMessage tm = session.createTextMessage(m.toJson());
			producer.send(tm);
			// ObjectMessage om = session.createObjectMessage(m);
			// producer.send(om);
		} finally {
			Thread.sleep(1000 * 5);
			connection.close();
		}
	}
}